function onError(error) {
  console.error(`Error: ${error}`);
}
async function getCurrentTab() {
  const tab = await browser.tabs.query({
    currentWindow: true,
    active: true
  })
  return tab[0]
}
function changeDebugMode(tab) {
  browser.tabs.sendMessage(
    tab.id,
    new Message(
     { from: LayerType.BACKGROUND,
      to: LayerType.CONTENT,
      content: `${Configs.app.name}Configs.debug = !${Configs.app.name}Configs.debug`,
      responseTo: LayerType.BACKGROUND,
      responseCall: 'pageActioniconColor',
      version: 0,}
    )
  ).then(response => {
   
  }).catch(onError);
}

browser.pageAction.onClicked.addListener(async () => {
  const tab = await getCurrentTab();
  changeDebugMode(tab)
});


async function pageActioniconColor() {
  // debugger
  sendMessage(
    new Message({
      from: LayerType.BACKGROUND,
      to: LayerType.CONTENT,
      content: `${Configs.app.name}Configs.debug`,
      responseTo: LayerType.BACKGROUND,
      responseCall: 'iconColorReturn',
      version: 0,
    }))
}

browser.runtime.onMessage.addListener(/**@param {Message} request */async function (request, sender) {
  // debugger
  if (request?.to === LayerType.BACKGROUND && request?.responseCall) {
    switch (request.responseCall) {
      case "pageActioniconColor":
        await pageActioniconColor()
        break;
      case "iconColorReturn": {
        const tab = await getCurrentTab();
        Configs.isDebug=request.content
        if (request.content) browser.pageAction.setIcon(
          {
            tabId: tab.id,
            path: {
              "48": "icons/message-48-g.png"
            }
          }
        )
        else browser.pageAction.setIcon({

          tabId: tab.id,
          path: {
            "48": "icons/message-48.png"
          }
        })
        break
      }
      case "getAppName":
       {
        //  debugger
         /**@type {Configs} Configs*/
        Configs.app.name = request.content
        break
      }
      default:
        break;
    }
  }
})


async function sendMessage(message) {
  const tabs = await browser.tabs.query({
    currentWindow: true,
    active: true
  });
  for (let tab of tabs) {
    browser.tabs.sendMessage(
      tab.id,
      message
    ).then(response => {}).catch(onError);
  }
}